﻿/**
 * Peter
 * Created by: Peter Development Team
 *    http://peter.codeplex.com/
 * 
 * GNU General Public License version 2 (GPLv2)
 *    http://peter.codeplex.com/license
 *
 *  This code is provided on an AS IS basis, with no WARRANTIES,
 *  CONDITIONS or GUARANTEES of any kind.
 *
 **/

using System;
using System.Windows.Threading;

namespace Peter.Common.Services
{
   /// <summary>
   /// A base timer service, implementing the ITimerService interface.
   /// </summary>
   public class TimerService : ITimerService
   {
      private readonly DispatcherTimer m_Timer;

      /// <summary>
      /// Initializes a new timer service.
      /// </summary>
      public TimerService ()
      {
         this.m_Timer  = new DispatcherTimer (DispatcherPriority.Normal, Dispatcher.CurrentDispatcher);
      }

      /// <summary>
      /// Timer interval in milliseconds.
      /// </summary>
      public double Interval
      {
         get { return this.m_Timer.Interval.Milliseconds; }
         set { this.m_Timer.Interval = TimeSpan.FromMilliseconds (value); }
      }

      /// <summary>
      /// Callback function. It will execute when the timer interval has elapsed.
      /// </summary>
      public EventHandler OnTimerTick { get; set; }

      /// <summary>
      /// Starts the timer.
      /// </summary>
      /// <exception cref="InvalidOperationException">
      /// There has to be one Timer Tick loaded to start the timer.
      /// </exception>
      public void Start ()
      {
         if (this.OnTimerTick == null)
            throw new InvalidOperationException ("No Timer Tick delegate has been loaded");
         m_Timer.Tick += this.OnTimerTick;
         m_Timer.Start ();
      }

      /// <summary>
      /// Stops the Timer.
      /// </summary>
      public void StopTimer ()
      {
         m_Timer.Stop ();
         if (this.OnTimerTick != null)
            m_Timer.Tick -= this.OnTimerTick;
      }
   }
}
